﻿using System;
using System.Linq;
using System.Web;
using Domino;
using System.Collections.Specialized;
using System.IO;
using System.Collections;

namespace NotesCommonProjects
{
    /// <summary>NOTES_000：總務用品機器人API</summary>
    /// SIP_Num = SIP號碼。
    /// PPS_CODE = 員工編號。
    /// Command = QR Code掃描機器人傳來的ccmd字串

    public class RobotStationery : IHttpHandler
    {
        //宣告Notes物件
        //總務用品申請單
        public NotesSession session;
        public NotesDatabase db;
        public NotesView view;
        public NotesView stationery_1_view;
        public NotesDocument temp_doc;
        public NotesDocument stationery_doc;
        public NotesDocument robot_doc;
        public NotesDocument new_doc;
        public NotesDocument first_doc_for_debug;
        public NotesDocumentCollection all_doc;
        public NotesItem item;

        //參考資料庫
        public NotesDatabase refe0_db;
        public NotesView id_view;
        public NotesDocument refe_doc;

        //簽核流程
        public NotesDatabase sapproval_db;
        public NotesView approve_key_view;
        public NotesDocument approve_doc;

        //宣告機器人丟來的資料
        //public string user_name_from_robot = "黃鴻仁";
        //public string supply_category = "tKeyWord=Gifts";
        //public string supply_item = "tSubType=贈禮品&tName=烏魚子&tSpec=單一規格";
        //public string supply_category = "tType=文具用品";
        //public string supply_item = "tSubType=筆類&tName=筆心&tSpec=自動鉛筆心";
        //public string supply_amount = "nQty=3";

        public string user_name_from_robot = null;
        public string sip_num = null;
        public string cmd = null;
        public string pps_code = null;

        public string robot_remark = "從iSender總務用品申請機器人 申請";
        public DateTime ProcessedTime1 = new DateTime();
        public DateTime ProcessedTime2 = new DateTime();

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                HttpRequest req = context.Request;

                //取得QR code 掃描機器人的WebService POST過來的參數
                sip_num = req.Form["SIP_Num"];
                pps_code = req.Form["PPS_CODE"];
                cmd = HttpUtility.UrlDecode(req.Form["Command"]);

                //cmd string for debug
                //BEGIN&TKEYWORD=PRINT&TSUBTYPE=名片&TNAME=雙面雙色名片&TSPEC=請附樣本&NQTY=1&END
                //using (StreamWriter sw = new StreamWriter("C:\\cmd_string_for_debug.txt"))
                //    sw.WriteLine(cmd);

                //建立NotesSession
                session = new NotesSession();

                //Initialize方法會自動抓目前系統登入使用的Notes id檔, 並要求輸入密碼
                //session.Initialize(NotesCF.MyIdPassword);
                session.Initialize(NotesCF.AutoCCPTIdPassword); //AutoCCPT

                //檢查pps_code
                if (!CheckPPSCode(pps_code))    //PPS_CODE為空
                {
                    string LogDir = NotesCF.StationeryLogDir;
                    string FileName = DateTime.Now.ToString("yyyy_MM_dd") + ".txt";

                    //申請失敗
                    //因PPS_CODE為空 只好用SIP_NUM呼叫機器人說話
                    FormUpload.RobotTextSend2(sip_num, NotesCF.FailedMessage2);

                    //寫入Log
                    string LogContext = "【申請失敗】 【參考資料庫中沒有員工編號】 【服務使用者："
                                + sip_num + "】";
                    NotesCF.WriteLog(NotesCF.StationeryLogDir, LogContext);
                }

                //操作Notes文件
                //user_name_from_robot = GetChineseName(pps_code, true);
                user_name_from_robot = GetChineseName2(pps_code);

                if (CheckCommand(cmd))
                {
                    if (user_name_from_robot != "" && cmd != "DELETE")
                    {
                        //取得指定位置的NotesDatabase
                        db = session.GetDatabase(NotesCF.TNotes01, NotesCF.StationeryDatabase, false);//總務用品申請單

                        //取得指定的NotesView
                        view = db.GetView("vStatus");

                        //取得所有文件
                        temp_doc = view.GetFirstDocument();
                        first_doc_for_debug = view.GetFirstDocument();
                        while (temp_doc != null)
                        {
                            //找尋機器人範本文件
                            var v = temp_doc.GetItemValue("CNS_Requestor");
                            if (v[0] == NotesCF.SampleDocumnetRequester)
                            {
                                robot_doc = temp_doc;
                                break;
                            }
                            else
                            {
                                NotesDocument temp_doc_release = temp_doc;
                                temp_doc = view.GetNextDocument(temp_doc_release);
                                NotesCF.ReleaseComObject(ref temp_doc_release);
                            }
                        }

                        //建立新的空白文件
                        new_doc = db.CreateDocument();

                        //複製範本文件所有NotesItem到新文件(值也會複製過去)
                        robot_doc.CopyAllItems(new_doc, true);

                        //執行Postopen事件
                        Postopen();

                        //初始化欄位預設值
                        InitializeColumns();

                        //計算表單內的"計算欄位"和"寫作時計算欄位"
                        ComputeCaculatedColumns();

                        //帶入Web Service傳來的參數
                        EditColumns();

                        //執行寄送申請單事件
                        SendRequest();

                        //執行轉譯欄位程式碼
                        TranslateColumns();

                        //計算此文件是否符合規範
                        //if (new_doc.ComputeWithForm(false, false))
                        //{
                        new_doc.Save(true, true);    //將文件存入資料庫
                        //}

                        //回傳訊息到機器人中
                        NameValueCollection cmd_query_string = HttpUtility.ParseQueryString(cmd);
                        string RequestItemName = cmd_query_string.GetValues("tName")[0];
                        string RequestItemSpec = cmd_query_string.GetValues("tSpec")[0];

                        FormUpload.RobotTextSend(pps_code, NotesCF.SuccessMessage(RequestItemName, RequestItemSpec));

                        //寫入Log
                        string LogContext = "【申請成功】 【服務使用者：" + GetChineseName2(pps_code)
                        + "】 【Command內容：" + cmd + "】 【Notes文件處理時間：" + ProcessedTime2.ToString()
                        + "】 【Notes ID：" + new_doc.NoteID + "】";

                        NotesCF.WriteLog(NotesCF.StationeryLogDir, LogContext);
                    }
                    else if (cmd == "DELETE")   //撤銷上一筆申請
                    {
                        string LogDir = NotesCF.StationeryLogDir;
                        string FileName = DateTime.Now.ToString("yyyy_MM_dd") + ".txt";
                        if (NotesCF.CheckLogFile(LogDir, FileName))
                        {

                            //1. 用user_name_from_robot到log檔中找出 使用者的最新一筆log
                            FileStream fs = new FileStream(LogDir + FileName, FileMode.Open, FileAccess.Read);
                            StreamReader sr = new StreamReader(fs);
                            ArrayList SuccessLog = new ArrayList();
                            ArrayList RepealLog = new ArrayList();
                            ArrayList NonRepealedLog = new ArrayList();

                            while (sr.Peek() >= 0)
                            {
                                string temp = sr.ReadLine();

                                if (temp.Contains("【申請成功】") && temp.Contains(user_name_from_robot))
                                    SuccessLog.Add(temp);
                                else if (temp.Contains("【撤銷成功】") && temp.Contains(user_name_from_robot))
                                    RepealLog.Add(temp);
                            }

                            //釋放檔案資源
                            sr.Dispose();
                            fs.Dispose();

                            //【申請成功】 【服務使用者：周正欣】 【Command內容：BEGIN&TKEYWORD=GIFTS&TSUBTYPE=贈禮品&TNAME=烏魚子&TSPEC=單一規格&NQTY=1&END】
                            //【Notes ID：5E282】 【Notes文件處理時間：2014/4/18 上午 09:39:28】

                            //【撤銷成功】 【服務使用者：周正欣】 
                            //【Notes ID：5E282】 【Notes文件處理時間：2014/4/18 上午 09:39:28】

                            //判斷無撤銷成功紀錄 or 最後一筆成功申請沒被撤銷
                            bool IsRepealed = false;

                            SuccessLog.Reverse();
                            RepealLog.Reverse();

                            //找出可撤銷的文件
                            for (int i = 0; i < SuccessLog.Count; i++)
                            {
                                int NotesidIndex = SuccessLog[i].ToString().IndexOf("Notes ID：") + "Notes ID：".Length;
                                string SuccessNotesid = SuccessLog[i].ToString().Substring(NotesidIndex, SuccessLog[i].ToString().LastIndexOf("】") - NotesidIndex);

                                for (int j = 0; j < RepealLog.Count; j++)
                                {
                                    NotesidIndex = RepealLog[j].ToString().IndexOf("Notes ID：") + "Notes ID：".Length;
                                    string RepealNotesid = RepealLog[j].ToString().Substring(NotesidIndex, RepealLog[j].ToString().LastIndexOf("】") - NotesidIndex);

                                    if (SuccessNotesid == RepealNotesid)
                                    {
                                        IsRepealed = true;
                                    }
                                }

                                if (!IsRepealed)
                                {
                                    NonRepealedLog.Add(SuccessLog[i].ToString());
                                }

                                IsRepealed = false;
                            }

                            //有文件可撤銷
                            if (NonRepealedLog.Count > 0)
                            {
                                int NotesidIndex = NonRepealedLog[0].ToString().IndexOf("Notes ID：") + "Notes ID：".Length;
                                string DeleteNotesDocumentID = NonRepealedLog[0].ToString().Substring(NotesidIndex, NonRepealedLog[0].ToString().LastIndexOf("】") - NotesidIndex);

                                //2. 用Notes ID 找到文件 檢查簽核狀態
                                db = session.GetDatabase(NotesCF.TNotes01, NotesCF.StationeryDatabase, false);
                                view = db.GetView("vStatus");
                                temp_doc = view.GetFirstDocument();
                                stationery_doc = null;
                                while (temp_doc != null)
                                {
                                    if (temp_doc.NoteID == DeleteNotesDocumentID)
                                    {
                                        stationery_doc = temp_doc;
                                        break;
                                    }
                                    else
                                    {
                                        NotesDocument temp_doc_release = temp_doc;
                                        temp_doc = view.GetNextDocument(temp_doc_release);
                                        NotesCF.ReleaseComObject(ref temp_doc_release);
                                    }
                                }

                                if (stationery_doc != null)
                                {
                                    //檢查文件的簽核狀態
                                    if (stationery_doc.GetItemValue("Status")[0] == "簽核中")
                                    {
                                        bool IsRemoveSuccess = false;
                                        IsRemoveSuccess = stationery_doc.Remove(true);

                                        if (IsRemoveSuccess)
                                        {
                                            //撤銷成功
                                            //string RequestItemName = stationery_doc.GetItemValue("tName1")[0].ToString();
                                            //string RequestItemSpec = stationery_doc.GetItemValue("tSpec1")[0].ToString();

                                            //FormUpload.RobotTextSend(pps_code, NotesCF.DeleteLastRequestSuccessMessage(RequestItemName, RequestItemSpec));
                                            FormUpload.RobotTextSend(pps_code, NotesCF.DeleteLastRequestSuccessMessage);

                                            //寫入Log
                                            string LogContext = "【撤銷成功】 【服務使用者：" + GetChineseName2(pps_code)
                                                + "】 【Notes ID：" + DeleteNotesDocumentID + "】";
                                            NotesCF.WriteLog(NotesCF.StationeryLogDir, LogContext);
                                        }
                                        else  //NotesDocument.Remove執行失敗
                                        {
                                            //撤銷上一筆申請失敗
                                            FormUpload.RobotTextSend(pps_code, NotesCF.DeleteLastRequestFailedMessage);

                                            //寫入Log
                                            string LogContext = "【撤銷失敗】 【NotesDocument.Remove執行失敗】 【服務使用者："
                                                + GetChineseName2(pps_code) + "】 【Notes ID：" + DeleteNotesDocumentID + "】";
                                            NotesCF.WriteLog(NotesCF.StationeryLogDir, LogContext);
                                        }
                                    }
                                    else  //文件狀態不是"簽核中"
                                    {
                                        //撤銷上一筆申請失敗
                                        FormUpload.RobotTextSend(pps_code, NotesCF.DeleteLastRequestFailedMessage2);

                                        //寫入Log
                                        string LogContext = "【撤銷失敗】 【文件狀態不是\"簽核中\"】 【服務使用者："
                                            + GetChineseName2(pps_code) + "】 【Notes ID：" + DeleteNotesDocumentID + "】";
                                        NotesCF.WriteLog(NotesCF.StationeryLogDir, LogContext);
                                    }
                                }
                                else  //stationery_doc為空
                                {
                                    //撤銷上一筆申請失敗
                                    FormUpload.RobotTextSend(pps_code, NotesCF.DeleteLastRequestFailedMessage);

                                    //寫入Log
                                    string LogContext = "【撤銷失敗】 【欲刪除的NotesDocument不在Notes系統中】 【服務使用者："
                                        + GetChineseName2(pps_code) + "】 【Notes ID：" + DeleteNotesDocumentID + "】";
                                    NotesCF.WriteLog(NotesCF.StationeryLogDir, LogContext);
                                }
                            }
                            else  //沒有撤銷紀錄或所有申請成功的紀錄都被撤銷了
                            {
                                //撤銷上一筆申請失敗
                                FormUpload.RobotTextSend(pps_code, NotesCF.DeleteLastRequestFailedMessage);

                                //寫入Log
                                string LogContext = "【撤銷失敗】 【沒有申請紀錄或所有申請成功的紀錄都被撤銷了】 【服務使用者："
                                    + GetChineseName2(pps_code) + "】";
                                NotesCF.WriteLog(NotesCF.StationeryLogDir, LogContext);
                            }
                        }
                        else  //今天還沒有產生Log文件
                        {
                            //撤銷上一筆申請失敗
                            FormUpload.RobotTextSend(pps_code, NotesCF.DeleteLastRequestFailedMessage3);

                            //寫入Log
                            string LogContext = "【撤銷失敗】 【只能撤銷當日的申請單】 【服務使用者："
                                + GetChineseName2(pps_code) + "】";
                            NotesCF.WriteLog(NotesCF.StationeryLogDir, LogContext);
                        }
                    }
                }
                else  //有參數為空 (使用者沒按照流程點選圖片)  或點選兩樣以上物品
                {
                    string LogDir = NotesCF.StationeryLogDir;
                    string FileName = DateTime.Now.ToString("yyyy_MM_dd") + ".txt";

                    //申請失敗
                    FormUpload.RobotTextSend(pps_code, NotesCF.FailedMessage);

                    //寫入Log
                    string LogContext = "【申請失敗】 【有參數為空或點選兩樣以上物品】 【服務使用者："
                                + GetChineseName2(pps_code) + "】";
                    NotesCF.WriteLog(NotesCF.StationeryLogDir, LogContext);
                }
            }
            catch (Exception ex)
            {
                //總務用品申請單添加失敗
                FormUpload.RobotTextSend(pps_code, NotesCF.ErrorMessage);

                //寫入Log
                string LogContext = "【發生例外】 【服務使用者：" + GetChineseName2(pps_code)
                    + "】 【錯誤函式：" + ex.TargetSite.ToString() + "】 【錯誤訊息："
                    + ex.Message + "】 【例外完整訊息：" + ex.ToString() + "】";
                NotesCF.WriteLog(NotesCF.StationeryLogDir, LogContext);
            }
        }

        //檢查POST過來的參數
        public bool CheckPPSCode(string pps_code)
        {
            try
            {
                if (pps_code != null)
                {
                    if (GetChineseName2(pps_code) != "")
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            catch (NullReferenceException)
            {
                return false;
            }
        }
        public bool CheckCommand(string cmd)
        {
            try
            {
                if (cmd != "DELETE")
                {
                    NameValueCollection cmd_query_string = HttpUtility.ParseQueryString(cmd);

                    //檢查是否有值
                    //檢查QueryString內的值是否合法(只有一項內容)
                    if (cmd_query_string.GetValues("tSubType")[0] != null && cmd_query_string.GetValues("tName")[0] != null
                        && cmd_query_string.GetValues("tSpec")[0] != null && cmd_query_string.GetValues("nQty")[0] != null
                        && cmd_query_string.GetValues("tSubType").Count() == 1 && cmd_query_string.GetValues("tName").Count() == 1
                        && cmd_query_string.GetValues("tSpec").Count() == 1 && cmd_query_string.GetValues("nQty").Count() == 1)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return true;
                }
            }
            catch (NullReferenceException)
            {
                return false;
            }
        }

        //Notes事件
        private void Postopen()
        {
            //Formula
            //ERequestor_A : @UserName
            //Author_A : @UserName
            ////@UserName = CH Chou/MI/T/CCP                  ↓
            ////@DbLookup("";"DNOTES01":"refe0.nsf";"ID";"CH Chou/MI/T/CCP";5) = 周正欣

            //C#
            new_doc.GetFirstItem("ERequestor_A").Values = GetID(user_name_from_robot);
            new_doc.GetFirstItem("Author_A").Values = GetID(user_name_from_robot);

            //LotusScript
            //doc.tRequestor=Evaluate("@Name([CN];ERequestor_A)",doc)

            //C#
            new_doc.GetFirstItem("tRequestor").Values = GetEnglishName(GetID(user_name_from_robot));

            //LotusScript
            //doc.tFactory=docS.Unit1   '廠別
            //doc.tDept=docS.Unit2  '部門別
            //doc.tDivision=docS.Unit3  '課別

            //C#
            new_doc.GetFirstItem("tFactory").Values = refe_doc.GetItemValue("Unit1")[0];
            new_doc.GetFirstItem("tDept").Values = refe_doc.GetItemValue("Unit2")[0];
            new_doc.GetFirstItem("tDivision").Values = refe_doc.GetItemValue("Unit3")[0];

            //LotusSctipt
            //GET 總務用品系統承辦人之 UserName 及 流程(Flow) 總階段數
            //Set db2= New NotesDatabase(db.server,"SAPPROVAL.NSF")
            //Set view=db2.getview("Approve_Key_View")
            //viewkey=doc.SystemName(0) & doc.tFactory(0) & doc.tDept(0) & doc.tDivision(0) & "發送"
            //Set doc2=view.GetDocumentByKey(viewkey)

            //C#
            sapproval_db = session.GetDatabase(NotesCF.TNotes01, NotesCF.SapprovalDatabase, false);
            approve_key_view = sapproval_db.GetView("Approve_Key_View");
            temp_doc = null;
            approve_doc = null;
            string viewkey = new_doc.GetItemValue("SystemName")[0] + new_doc.GetItemValue("tFactory")[0] +
                new_doc.GetItemValue("tDept")[0] + new_doc.GetItemValue("tDivision")[0] + "發送";
            approve_doc = approve_key_view.GetDocumentByKey(viewkey);


            //LotusScript
            //doc.tFlowNo = doc2.tStatus(0)
            //doc.Handler=doc2.aUsername
            //zz=doc2.altUsername		
            //Set item = doc.GetFirstItem( "tHandler" )
            //Call item.AppendToTextList(doc.Handler) 
            //Call item.AppendToTextList(zz) 
            //doc.tHandler= Evaluate("@unique(tHandler)", doc)		
            //doc.tStatusCode=doc2.tStatus	

            //C#
            new_doc.GetFirstItem("tFlowNo").Values = approve_doc.GetItemValue("tStatus")[0];
            new_doc.GetFirstItem("Handler").Values = approve_doc.GetItemValue("aUserName")[0];
            new_doc.GetFirstItem("tHandler").AppendToTextList(new_doc.GetItemValue("Handler")[0]);
            new_doc.GetFirstItem("tHandler").AppendToTextList(approve_doc.GetItemValue("altUsername")[0]);
            new_doc.GetFirstItem("tHandler").Values = session.Evaluate("@unique(tHandler)", new_doc);
            new_doc.GetFirstItem("tStatusCode").Values = approve_doc.GetItemValue("tStatus")[0];
        }
        private void InitializeColumns()
        {
            //有初值的可編輯欄位們
            //隱藏欄位
            new_doc.GetFirstItem("tStatusCode").Values = "1";
            new_doc.GetFirstItem("IsProcessed").Values = "0";
            new_doc.GetFirstItem("IsPurchased").Values = "0";
            new_doc.GetFirstItem("MailFlag").Values = "初始狀態";

            //表單欄位
            new_doc.GetFirstItem("Status").Values = "寫作中";
            new_doc.GetFirstItem("tKeyWord").Values = "Stationery";
            for (int i = 1; i <= 11; i++)
            {
                new_doc.GetFirstItem("nQty" + i.ToString()).Values = "0";
                new_doc.GetFirstItem("tUser" + i.ToString()).Values = user_name_from_robot;
            }
            new_doc.GetFirstItem("TotalPrice").Values = "0";
            //new_doc.GetFirstItem("XMLText").Values = "";
            new_doc.ReplaceItemValue("XMLText", "");
            new_doc.GetFirstItem("tFlag").Values = "";
            new_doc.GetFirstItem("Form").Values = "RequestForm";
        }
        private void ComputeCaculatedColumns()
        {
            //計算欄位們
            //隱藏欄位
            new_doc.GetFirstItem("SystemName").Values = "總務用品申請單";
            new_doc.GetFirstItem("ERequestor_A").Values = GetID(user_name_from_robot);
            new_doc.GetFirstItem("Author_A").Values = GetID(user_name_from_robot);

            new_doc.GetFirstItem("tApproveNextCNSName").Values = GetChineseName(new_doc.GetItemValue("ApproveNext")[0]);
            new_doc.GetFirstItem("tRejectToCNSName").Values = GetChineseName(new_doc.GetItemValue("RejectTo")[0]);
            new_doc.GetFirstItem("tHandlerCNSName").Values = GetChineseName(new_doc.GetItemValue("Handler")[0]);

            new_doc.GetFirstItem("ProcessedTime").Values = session.Evaluate("@Now", new_doc);
            ProcessedTime1 = new_doc.GetFirstItem("ProcessedTime").Values[0];  //為了要實現撤銷上一筆申請功能加的

            //奇怪找不到此Item        ↓↓
            //new_doc.GetFirstItem("xKeyWord").Values = new_doc.GetItemValue("tKeyWord")[0] + "_1";
            //new_doc.GetFirstItem("UN").Values = GetEnglishName(GetID(user_name_from_robot));

            new_doc.GetFirstItem("CNS_UN").Values = user_name_from_robot;

            //表單欄位
            new_doc.GetFirstItem("CNS_Requestor").Values = user_name_from_robot;
            new_doc.GetFirstItem("dDate").Values = session.Evaluate("@Now", new_doc);
            new_doc.GetFirstItem("CRequestor").Values = GetEnglishName(GetID(user_name_from_robot));

            //奇怪找不到此Item        ↓↓
            //new_doc.GetFirstItem("Xserialno").Values = new_doc.GetItemValue("serialno")[0];

            new_doc.GetFirstItem("dDate").Values = session.Evaluate("@Now", new_doc);

            for (int i = 1; i <= 11; i++)
            {
                new_doc.GetFirstItem("tUnit" + i.ToString()).Values = GetUnitName(
                    new_doc.GetItemValue("tKeyWord")[0] + "_1",
                    new_doc.GetItemValue("tName" + i.ToString())[0]);
            }

            new_doc.ReplaceItemValue("xProcDate", "");
            new_doc.ReplaceItemValue("xProcTime", "");
            new_doc.ReplaceItemValue("xProcName", "");
            new_doc.ReplaceItemValue("xProcAct", "");
            new_doc.GetFirstItem("xApprove_Opinion").Values = new_doc.GetItemValue("CNS_UN")[0] +
                session.Evaluate("@Now", new_doc)[0] + new_doc.GetItemValue("tApprove_Opinion")[0] +
                "  ------ 填寫申請單";
        }
        private void EditColumns()
        {
            /*
             public string user_name_from_robot = "周正欣";
             public string supply_category = "tKeyWord=贈禮品";
             public string supply_item = "tSubType=贈禮品&tName=烏魚子&tSpec=單一規格";
             //public string supply_category = "tType=文具用品";
             //public string supply_item = "tSubType=筆類&tName=筆心&tSpec=自動鉛筆心";
             public string supply_amount = "nQty=2";
             public string robot_remark = "從iSender總務用品申請機器人 申請";
             */

            NameValueCollection supply_category_query_string = HttpUtility.ParseQueryString(cmd);
            NameValueCollection supply_item_query_string = HttpUtility.ParseQueryString(cmd);
            NameValueCollection supply_amount_query_string = HttpUtility.ParseQueryString(cmd);

            string temp = supply_category_query_string.GetValues("tKeyWord")[0];
            string lowercase_category_name = null;

            /*
             @If(tKeyWord="Stationery";"文具用品";
             * tKeyWord="Paper";"事務機器用紙";
             * tKeyWord="Gifts";"贈禮品";
             * tKeyWord="Elecs";"電器零件";
             * tKeyWord="Misc";"其他";
             * tKeyWord="Print";"印刷品";"")
             */

            switch (temp)
            {
                case "STATIONERY":
                    temp = "文具用品";
                    lowercase_category_name = "Stationery";
                    break;
                case "PAPER":
                    temp = "事務機器用紙";
                    lowercase_category_name = "Paper";
                    break;
                case "GIFTS":
                    temp = "贈禮品";
                    lowercase_category_name = "Gifts";
                    break;
                case "ELECS":
                    temp = "電器零件";
                    lowercase_category_name = "Elecs";
                    break;
                case "MISC":
                    temp = "其他";
                    lowercase_category_name = "Misc";
                    break;
                case "PRINT":
                    temp = "印刷品";
                    lowercase_category_name = "Print";
                    break;
            }

            new_doc.GetFirstItem("tKeyWord").Values = lowercase_category_name;

            new_doc.ReplaceItemValue("tType", temp);

            new_doc.GetFirstItem("tSubType1").Values = supply_item_query_string.GetValues("tSubType");
            new_doc.GetFirstItem("tName1").Values = supply_item_query_string.GetValues("tName");
            new_doc.GetFirstItem("tSpec1").Values = supply_item_query_string.GetValues("tSpec");
            new_doc.GetFirstItem("nQty1").Values = supply_amount_query_string.GetValues("nQty");
            new_doc.GetFirstItem("rRemark1").Values = robot_remark;
        }
        private void SendRequest()
        {
            //LotusScript
            //doc.tStatusCode="2"
            //Set db2= New NotesDatabase(db.server,"SAPPROVAL.NSF")
            //Set view1=db2.getview("Approve_Status_View")
            //viewkey=doc.SystemName(0) & doc.tFactory(0) & doc.tDept(0) & doc.tDivision(0) & doc.tStatusCode(0)

            //C#
            new_doc.GetFirstItem("tStatusCode").Values = "2";
            NotesView approve_status_view = sapproval_db.GetView("Approve_Status_View");
            string viewkey = new_doc.GetItemValue("SystemName")[0] + new_doc.GetItemValue("tFactory")[0] +
                new_doc.GetItemValue("tDept")[0] + new_doc.GetItemValue("tDivision")[0] +
                new_doc.GetItemValue("tStatusCode")[0];

            //LotusScript
            //Set doc3=view1.GetDocumentByKey(viewkey)
            //Set doc4=view1.GetNextDocument(doc3)

            //C#
            NotesDocument approve_next_doc = approve_status_view.GetDocumentByKey(viewkey);
            NotesDocument next_approve_next_doc = approve_status_view.GetNextDocument(approve_next_doc);

            //LotusScript
            //doc.ApproveNext=doc3.aUsername
            //doc.tApproveNext=Evaluate("@Name([CN];ApproveNext)",doc)
            //doc.WhoCheck=doc.tApproveNext

            //C#
            new_doc.GetFirstItem("ApproveNext").Values = approve_next_doc.GetItemValue("aUsername")[0];
            new_doc.GetFirstItem("tApproveNext").Values = session.Evaluate("@Name([CN];ApproveNext)", new_doc);
            new_doc.GetFirstItem("WhoCheck").Values = new_doc.GetItemValue("tApproveNext")[0];

            //LotusScript
            //Call uidoc.refresh

            //C#
            ComputeCaculatedColumns();

            //LotusScript
            //Set emaildoc=New NotesDocument(db)
            //Set rtitem=New NotesRichTextItem(emaildoc, "Body")
            //emaildoc.SendTo=doc.ApproveNext(0)
            //emaildoc.subject="請簽核" & doc.CNS_Requestor(0) & "之總務用品申請單 !!"

            //C#
            NotesDocument email_doc = db.CreateDocument();
            NotesRichTextItem rich_text_item = email_doc.CreateRichTextItem("Body");
            email_doc.ReplaceItemValue("SendTo", new_doc.GetItemValue("ApproveNext")[0]);
            email_doc.ReplaceItemValue("Subject", "請簽核" +
                new_doc.GetItemValue("CNS_Requestor")[0] + "之總務用品申請單 !!");

            //LotusScript
            //doc.Status="簽核中"
            //doc.tStatusCode="2"
            //doc.tStatusCode_Next="3"
            //doc.tStatusCode_Prev="1"
            //doc.ProcessedTime=Now()
            //doc.xApprove_Opinion=doc.xApprove_Opinion(0) & Chr(13) & doc.CNS_UN(0) & Now() & "    送簽" 
            //doc.tApprove_Opinion=""

            //C#
            new_doc.GetFirstItem("Status").Values = "簽核中";
            new_doc.GetFirstItem("tStatusCode").Values = "2";
            new_doc.GetFirstItem("tStatusCode_Next").Values = "3";
            new_doc.GetFirstItem("tStatusCode_Prev").Values = "1";
            new_doc.GetFirstItem("ProcessedTime").Values = session.Evaluate("@Now", new_doc);
            ProcessedTime2 = new_doc.GetFirstItem("ProcessedTime").Values[0];  //為了要實現撤銷上一筆申請功能加的
            new_doc.GetFirstItem("xApprove_Opinion").Values = new_doc.GetItemValue("xApprove_Opinion")[0] +
                "\r" + new_doc.GetItemValue("CNS_UN")[0] + session.Evaluate("@Now", new_doc)[0] + "    送簽";
            new_doc.GetFirstItem("tApprove_Opinion").Values = "";

            //LotusScript
            //doc.xProcName=doc.xProcName(0) & doc.CNS_UN(0) & Chr(13)
            //doc.xProcDate=doc.xProcDate(0) & ServerDate() & Chr(13) 
            //doc.xProcTime=doc.xProcTime(0) & ServerTime() & Chr(13)
            //doc.xProcAct=doc.xProcAct(0) & "寄送申請單" & Chr(13)
            //doc.Author_A=doc.ApproveNext

            //C#
            new_doc.GetFirstItem("xProcName").Values = new_doc.GetItemValue("xProcName")[0] +
                new_doc.GetItemValue("CNS_UN")[0] + "\r";
            new_doc.GetFirstItem("xProcDate").Values = new_doc.GetItemValue("xProcDate")[0] +
                DateTime.Now.ToShortDateString() + "\r";
            new_doc.GetFirstItem("xProcTime").Values = new_doc.GetItemValue("xProcTime")[0] +
                DateTime.Now.ToString("HH:mm:ss tt") + "\r";
            new_doc.GetFirstItem("xProcAct").Values = new_doc.GetItemValue("xProcAct")[0] +
                "寄送申請單" + "\r";
            new_doc.GetFirstItem("Author_A").Values = new_doc.GetItemValue("ApproveNext")[0];

            //LotusScript
            //Call rtitem.AppendText("請連續按二下滑鼠或以空白鍵開啟文件查看總務用品申請單 !!")
            //Call rtitem.AddNewLine(1)
            //Call rtitem.AppendDocLink(doc, "連結至文件")
            //Call doc.save(True,True)
            //Call emaildoc.Send(False)
            //Call uidoc.save
            //Call uidoc.close

            //C#
            rich_text_item.AppendText("請連續按二下滑鼠或以空白鍵開啟文件查看總務用品申請單 !!");
            rich_text_item.AddNewLine(1);
            rich_text_item.AppendDocLink(new_doc, "連結至文件");

            //執行就存檔了!!
            new_doc.Save(true, true);

            //email_doc.ReplaceItemValue("SendTo", "CH Chou/MI/T/CCP");
            //執行就寄出了!!
            email_doc.Send(false);
        }
        private void TranslateColumns()
        {
            /*
             FIELD tNameSpecQty := tNameSpecQty;
             NSQ1:=tName1+";"+tSpec1+";"+@Text(nQty1);
             NSQ2:=tName2+";"+tSpec2+";"+@Text(nQty2);
             NSQ3:=tName3+";"+tSpec3+";"+@Text(nQty3);
             NSQ4:=tName4+";"+tSpec4+";"+@Text(nQty4);
             NSQ5:=tName5+";"+tSpec5+";"+@Text(nQty5);
             NSQ6:=tName6+";"+tSpec6+";"+@Text(nQty6);
             NSQ7:=tName7+";"+tSpec7+";"+@Text(nQty7);
             NSQ8:=tName8+";"+tSpec8+";"+@Text(nQty8);
             NSQ9:=tName9+";"+tSpec9+";"+@Text(nQty9);
             NSQ10:=tName10+";"+tSpec10+";"+@Text(nQty10);
             NSQ:=NSQ1+":"+NSQ2+":"+NSQ3+":"+NSQ4+":"+NSQ5+":"+NSQ6+":"+NSQ7+":"+NSQ8+":"+NSQ9+":"+NSQ10+":";
             @SetField("tNameSpecQty"; NSQ)
            */

            string NSQ = null;
            for (int i = 1; i <= 10; i++)
            {
                NSQ += new_doc.GetItemValue("tName" + i.ToString())[0] + ";" +
                    new_doc.GetItemValue("tSpec" + i.ToString())[0] + ";" +
                    new_doc.GetItemValue("nQty" + i.ToString())[0] + ":";
            }
            new_doc.GetFirstItem("tNameSpecQty").Values = NSQ;
        }

        //從參考資料庫取得欄位內容的函式
        //用notes id找english name
        public string GetEnglishName(string id)
        {
            int start_index = id.IndexOf("CN=") + 3;
            int end_index = id.IndexOf("/");
            string english_name = id.Substring(start_index, end_index - start_index);

            if (english_name != null)
                return english_name;
            else
                return "";
        }
        public string _GetChineseName(string input)
        {
            return GetNotesItemValue(session, NotesCF.TNotes01,
                NotesCF.ReferenceDatabase, "ID", "ID", "Name", input);
        }
        public string _GetChineseName2(string input)
        {
            return GetNotesItemValue(session, NotesCF.TNotes01, NotesCF.ReferenceDatabase,
                    "ID", "staffnu", "Name", input);
        }
        public string _GetID(string input)
        {
            return GetNotesItemValue(session, NotesCF.TNotes01,
                NotesCF.ReferenceDatabase, "ID", "Name", "ID", input);
        }
        public string GetUnitName(string key_word, string input)
        {
            return GetNotesItemValue(session, NotesCF.TNotes01,
                NotesCF.StationeryDatabase, key_word, "tName", "tUnit", input);
        }
        public string GetNotesItemValue(NotesSession session,
        string notes_server, string notes_database, string notes_view,
        string notes_key_item, string notes_value_item, string input)
        {
            if (input == null || input == "")
            {
                return "";
            }
            else
            {
                NotesDatabase db = session.GetDatabase(notes_server, notes_database, false);
                NotesView view = db.GetView(notes_view);
                NotesDocument temp_doc = view.GetFirstDocument();
                while (temp_doc != null)
                {
                    string v = temp_doc.GetItemValue(notes_key_item)[0];
                    if (v == input)
                    {
                        refe_doc = temp_doc;
                        break;
                    }
                    else
                    {
                        NotesDocument temp_doc_release = temp_doc;
                        temp_doc = view.GetNextDocument(temp_doc);
                        NotesCF.ReleaseComObject(ref temp_doc_release);
                    }
                    //找不到中文名的話
                    //寫在這裡
                }
                if (refe_doc == null)
                    return "";
                else if (refe_doc.GetItemValue(notes_value_item)[0] == null)
                    return "";
                else
                    return refe_doc.GetItemValue(notes_value_item)[0];
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        //轉換名字functions
        public string GetChineseName(string english_name)//english_name = ID(in Notes)
        {
            refe0_db = session.GetDatabase(NotesCF.TNotes01, NotesCF.ReferenceDatabase, false);
            id_view = refe0_db.GetView("robot_id_to_chinesename");
            refe_doc = id_view.GetDocumentByKey(english_name);

            if (refe_doc == null)
                return "";
            else if (refe_doc.GetItemValue("Name")[0] == null)
                return "";
            else
                return refe_doc.GetItemValue("Name")[0];
        }

        public string GetChineseName2(string pps_code)
        {
            refe0_db = session.GetDatabase(NotesCF.TNotes01, NotesCF.ReferenceDatabase, false);
            id_view = refe0_db.GetView("robot_ppscode_to_chinesename");
            refe_doc = id_view.GetDocumentByKey(pps_code);

            if (refe_doc == null)
                return "";
            else if (refe_doc.GetItemValue("Name")[0] == null)
                return "";
            else
                return refe_doc.GetItemValue("Name")[0];
        }

        public string GetID(string chinese_name)
        {
            refe0_db = session.GetDatabase(NotesCF.TNotes01, NotesCF.ReferenceDatabase, false);
            id_view = refe0_db.GetView("Name");
            refe_doc = id_view.GetDocumentByKey(chinese_name);

            if (refe_doc == null)
                return "";
            else if (refe_doc.GetItemValue("ID")[0] == null)
                return "";
            else
                return refe_doc.GetItemValue("ID")[0];
        }
    }
}